<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
    <basic-container class="myDesign">
        <avue-form-design style="height: 100vh"
                          ref="formDesign"
                          :show-github-star="false"
                          :toolbar="toolbar"
                          :storage="false"
                          :custom-fields="customFields"
                           @submit="handleSubmit2"
                           @aiCreate="handleAI"
                          @excelWjImport="handleExcelWjImport"
                           @preview2="handlePreview2"
                          :options="option">


<!--            <template #slot="toolbar-left"  >-->
<!--                <el-button link-->
<!--                           type="primary"-->
<!--                           icon="el-icon-download"-->
<!--                           @click="handleSubmit2">获取JSON2</el-button>-->
<!--            </template>-->

        </avue-form-design>

    </basic-container>





    <div>

        <el-drawer title="预览" v-model="previewVisible"    :visible.sync="drawer"   size="50%" append-to-body>

            <el-switch
                    v-model="previewType"
                    active-text="PC端"
                    inactive-text="移动端"
                    active-value="pc"
                    inactive-value="phone"
                    @change="changeUrl"
                  >
            </el-switch>


            <div :class="{ 'preview-box': previewType=='pc', 'phone-preview-box': previewType!='pc' }">
                <iframe  :src="previewUrl" ></iframe>
            </div>

        </el-drawer>

    </div>

    <el-dialog title="AI助手" v-model="isAIView" style="width:880px"  @close="isAIView=false" append-to-body>
        <el-container>
            <el-header>
                <el-input placeholder="请输入内容" v-model="aiText" class="ai-input-with-select" >
                </el-input>
                <el-button slot="append" icon="el-icon-search" @click="aiHander">AI</el-button>
            </el-header>
            <el-main>
                <avue-crud
                        :option="aiOption"
                        :data="aiTableData"
                        @row-save="rowAiSave"
                         @row-update="rowAiUpdate"
                         @row-del="rowAiDel"
                >

                </avue-crud>
            </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
            <el-button @click="isAIView = false">取消</el-button>
            <el-button type="primary" @click="autoFormHander">生成</el-button>
        </div>
    </el-dialog>

  <el-dialog title="Excel导入" v-model="isExcelWjView" style="width:250px"  @close="isExcelWjView=false" append-to-body>
    <el-container>
      <el-main>

        <div class="design-upload-file">
          <input type="file" class="input-file" multiple="false"  @change="handleFileJwUpload" >
          <span class="tip">上传</span>
        </div>

        <div style="margin-top: 10px;margin-bottom: 10px;" >
          <el-link  type="primary" underline="true"  href="http://testvod.5xuexi.com/wjmb.xlsx">下载模板</el-link>
        </div>
      </el-main>

    </el-container>


    <div slot="footer"  class="my-el-dialog-footer">
      <el-button @click="isExcelWjView = false">取消</el-button>
<!--      <el-button type="primary" @click="autoJwHander">生成</el-button>-->
    </div>
  </el-dialog>

</template>


<script>
    import {getFormModel, saveForm,publishForm} from "@/framework-admin/api/code/formmodel";
    import {customFields} from "./fieldsConfig";
    import {getAiFormCols} from '@/framework-core/api/ai'
    import { loadxlsxScript} from '@/framework-core/utils/util'
    import pinyin from 'js-pinyin'

    export default {

      data() {
        return {
          loadingInstance: null,
          isAIView: false,
          // uploadType:"1",
          aiText: "",
          isExcelWjView:false,
          aiOption: {
            "border": true,
            "index": true,
            "indexLabel": "#",
            "stripe": true,
            "menuAlign": "center",
            "align": "center",
            "searchMenuSpan": 6,
            grid: window.isMobile,
            addBtn: false,
            addRowBtn: true,
            cellBtn: true,
            gridSpan: 24,
            searchEnter: true,
            "column": [
              {
                "type": "input",
                "label": "名称",
                "prop": "label",
                "cell": true,
                "span": 12
              },
              {
                "type": "select",
                "label": "渲染类型",
                "dicData": [{"label": "文本", "value": "input"}, {
                  "label": "下拉框",
                  "value": "select"
                }, {"label": "日期", "value": "datetime"}, {"label": "数字", "value": "number"}],
                "prop": "type",
                "cell": true,
                "span": 12
              },
              {
                "type": "input",
                "label": "字典数据(在表单中修改)",
                "prop": "dicData",
                "span": 12
              }
            ]
          },
          aiTableData: [],
          previewVisible: false,
          previewType: "pc",
          previewUrl: window.location.href.replace("/form/design", "/form/preview"),
          toolbar: ['submit', 'generate', 'preview', 'import', 'clear'],
          option: {},
          defFormOption: {
            column: [{
              title: '警告',
              label: "警告",
              component: 'el-alert',
              labelWidth: '0px',
              span: 24,
              tips: '看我：自定义事件怎么用？',
              params: {title: '警告警告警告警告', type: 'success'},
              event: {
                close: () => {
                  console.log("alert关闭事件")
                }
              },
              prop: 'test1'
            }, {type: 'input', label: '单行文本', span: 24, display: true, prop: 'test2'}, {
              type: 'textarea',
              label: '多行文本',
              span: 24,
              display: true,
              prop: 'test3'
            }, {
              type: 'checkbox',
              label: '多选框组',
              dicData: [{label: '选项一', value: '0'}, {label: '选项二', value: '1'}, {label: '选项三', value: '2'}],
              span: 24,
              display: true,
              props: {label: 'label', value: 'value'},
              prop: 'test4'
            }],
            labelPosition: 'left',
            labelSuffix: '：',
            labelWidth: 120,
            gutter: 0,
            menuBtn: true,
            submitBtn: true,
            submitText: '提交',
            emptyBtn: true,
            emptyText: '清空',
            menuPosition: 'center'
          },
          formCode: "",
          type: 'design',
          formData: {"start": "2023年011月03日", "end": "2023年011月13日"},
          customFields: customFields
        };
      },
      created() {
        loadxlsxScript();
        window.deepClone = this.deepClone;
        pinyin.setOptions({checkPolyphone: false, charCase: 1});
        this.getFormInfo();
      },

      watch: {
        'option.column': {
          handler: function (val, oldval) {
            console.log('修改后', val, '修改前', oldval);
          },
          deep: true
        }
      },


      methods: {
        handleExcelWjImport() {
          if(!XLSX){
            this.$message.error("页面还没有加载完成，请稍后再试，如果多次不行请刷新页面")
            return
          }
          this.isExcelWjView = true;
        },
        handleFileJwUpload(event){
          const file = (event.target).files?.[0];
          if (file) {

            const reader = new FileReader();
            reader.onload = (e) => {
              let workbook = null
              try {
                workbook = XLSX.read(e.target.result, {type: 'binary'});
              } catch (e) {
                this.$message.error("问卷读取错误:" + e)
                if (e.indexOf("XLSX.read is not a function") >= 0) {
                  loadxlsxScript();
                }
                return
              }

              const sheetName = workbook.SheetNames[0];
              const worksheet = workbook.Sheets[sheetName];
              let formJsons = [];
              let typeStr = {
                "单选": "radio",
                "多选": "checkbox",
                "判断": "radio",
                "文本": "input",
                "数字": "number",
                "多行文本": "textarea"
              }
              const jsonList = XLSX.utils.sheet_to_json(worksheet, {header: 1});
              let text = "";
              let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
              for (let i = 0; i < 3; i++) {
                text += possible.charAt(Math.floor(Math.random() * possible.length));
              }

              for (let index = 2; index < jsonList.length; index++) {
                let jsonData = jsonList[index];
                let formJson = {}
                formJson.type = typeStr[jsonData[0]];
                if (!formJson.type) {
                  continue
                }
                formJson.prop = "a" + text + ("000" + index.toString()).slice(-3);
                formJson.label = jsonData[1];
                formJson.span = 24;
                formJson.display = true;
                if (formJson.type == "radio" || formJson.type == "checkbox") {
                  formJson.dicData = [];
                  let sortType = jsonData[2]
                  let lable = "";
                  let value = "";
                  let score = 0;
                  let isFx = false;
                  for (let n = 3; n < 8; n++) {
                    lable = jsonData[n];
                    if (lable === undefined || lable === "") {
                      continue
                    }
                    if (sortType == "无") {
                      value = lable
                    } else if (sortType == "正序") {
                      value = ++score;
                    } else if (sortType == "反序") {
                      value = --score;
                      isFx = true;
                    } else {
                      value = lable
                    }
                    formJson.dicData.push({label: lable, value: value+""})
                  }
                  if (isFx) {
                    for (let n = 0; n < formJson.dicData.length; n++) {
                      formJson.dicData[n].value = (formJson.dicData[n].value - value+1)+"";
                    }
                  }
                }
                this.option.column.push(formJson)
                this.isExcelWjView = false;
              }

            };
            reader.readAsBinaryString(file);
          }

        },
        autoJwHander(){
          this.isExcelWjView = false;
        },
        handleAI() {
          this.isAIView = true;

          // let cjson = {
          //     "columns": [{
          //         "label": "请假类型",
          //         "type": "select",
          //         "dicData": ["病假", "事假", "公假", "其他"],
          //         "comment": "请假的类型"
          //     }, {"label": "学生姓名", "type": "input", "comment": "请假学生的姓名"}, {
          //         "label": "学号",
          //         "type": "input",
          //         "comment": "请假学生的学号"
          //     }, {"label": "请假开始时间", "type": "datetime", "comment": "请假开始的时间"}, {
          //         "label": "请假结束时间",
          //         "type": "datetime",
          //         "comment": "请假结束的时间"
          //     }, {"label": "请假时长", "type": "number", "comment": "请假的总时长，单位可以是天、小时等，根据实际需求填写"}, {
          //         "label": "请假原因",
          //         "type": "input",
          //         "comment": "请假的具体原因"
          //     }, {
          //         "label": "审批状态",
          //         "type": "select",
          //         "dicData": ["待审批", "已批准", "已拒绝"],
          //         "comment": "当前请假的审批状态"
          //     }, {"label": "审批人", "type": "input", "comment": "审批该请假申请的人"}, {
          //         "label": "审批意见",
          //         "type": "input",
          //         "comment": "审批人对该请假申请的审批意见"
          //     }]
          // }
          // for (let cindex = 0; cindex < cjson.columns.length; cindex++) {
          //     cjson.columns[cindex].id = 10000+cindex
          // }
          // this.aiTableData = cjson.columns;
        },

        aiHander() {
          if (!this.aiText) {
            this.$message.error("请输入提示词")
            return
          }
          this.loading = true;
          getAiFormCols(this.aiText).then(response => {
            let cjson = response.data.data.data;
            cjson = JSON.parse(cjson);
            for (let cindex = 0; cindex < cjson.columns.length; cindex++) {
              cjson.columns[cindex].id = 10000 + cindex
            }
            this.aiTableData = cjson.columns;
            this.loading = false;
          }).catch(error => {
            this.$message.error(error.msg || error.message)
          })
        },
        autoFormHander() {
          if (this.aiTableData) {
            let columnsTemp = [];
            let propMap = {};
            for (let cindex = 0; cindex < this.aiTableData.length; cindex++) {
              let column = this.aiTableData[cindex];
              let columnTemp = {};
              columnTemp.label = column.label;
              let prop = pinyin.getCamelChars(column.label);
              let propIndex = propMap[prop];
              if (propIndex) {
                prop = prop + (propIndex + 1);
                propMap[prop] = (propIndex + 1);
              } else {
                propMap[prop] = 1;
              }
              columnTemp.prop = prop;

              columnTemp.type = column.type
              columnTemp.span = 12;
              columnTemp.display = true;
              columnTemp.labelWidth = 120;
              if ("申请人" == columnTemp.label) {
                columnTemp.sysParam = '{@{displayName}}';
              }
              if ("date" == columnTemp.type || "datetime" == columnTemp.type) {
                columnTemp.format = 'YYYY-MM-DD';
                columnTemp.valueFormat = 'YYYY-MM-DD';
              }
              if (column.dicData) {
                let dicTemps = [];
                for (let dicindex = 0; dicindex < column.dicData.length; dicindex++) {
                  let dic = column.dicData[dicindex];
                  dicTemps.push({"label": dic, "value": dic})
                }
                columnTemp.dicData = dicTemps;
              }
              columnsTemp.push(columnTemp)
            }
            this.option.column = columnsTemp;
            this.isAIView = false;
          }

        },
        rowAiDel(form, index, done) {
          done()
        },
        rowAiSave(form, done) {
          done()
        },
        rowAiUpdate(form, index, done, loading) {

          done();
        },
        handleSubmit2(data) {
          var datatemp = this.transformMyToAvueOptions(data, false, this);
          saveForm(datatemp, {
                id: this.formId
              }
          ).then(response => {
            if (response) {
              if (response.data.success) {

                this.$confirm("保存成功，是否去发布（如果数据结构发生变化则需要发布后才可以保存申请的数据，数据库表将会保留被删除的字段，请谨慎发布）", "提示", {
                  iconClass: "el-icon-question",//自定义图标样式
                  confirmButtonText: "发布",//确认按钮文字更换
                  cancelButtonText: "取消",//取消按钮文字更换
                  showClose: true,//是否显示右上角关闭按钮
                  type: "warning",//提示类型  success/info/warning/error
                }).then(() => {
                  this.getFormInfo();
                  publishForm({id: this.formId}
                  ).then(response => {
                    this.$message.success('发布成功')
                  }).catch(error => {
                    this.$message.error(error.msg || error.message)
                  })
                }).catch(() => {
                  this.getFormInfo();
                });
              } else {
                if (response.data.state == 401) {
                  this.$router.push({path: "/login"});
                } else {
                  this.$message.error(response.data.message || "保存出错")
                }
              }
            } else {
              this.$message.error("保存出错")
            }

          }).catch(error => {
            this.$message.error(error.msg || error.message)
          })

        },
        getFormInfo() {
          this.formId = this.$route.query.formId
          if (this.formId) {
            this.loadData(this.formId)
          } else {
            // this.$message.error('缺失options参数,请联系管理员')
            // this.$router.push({path: '/500'})
            this.option = this.deepClone(this.defFormOption);
          }


        },
        loadData(formId) {
          getFormModel(formId)
              .then((res) => {
                if (res.data) {
                  this.option = eval("(" + res.data.data.form.modelJson + ")") || this.deepClone(this.defFormOption);
                  if (this.option.length == 0) {
                    this.option = this.deepClone(this.defFormOption);
                  }
                } else {
                  this.$message.error('缺失options参数,请联系管理员')
                  this.$router.push({path: '/500'})
                }
              })
              .catch((err) => {
                this.$message.error(err.msg || err.message)
              })
              .finally(() => {
                this.loading = true
              })
        }
        ,
        transformMyToAvueOptions(data) {

          for (let i = 0; i < data.column.length; i++) {
            const col = data.column[i]
            if (col.type == 'group') {
              if (!data.group) data.group = []
              const group = {
                label: col.label,
                icon: col.icon,
                prop: col.prop,
                arrow: col.arrow,
                isGird: col.isGird,
                rowNum: col.rowNum,
                colNum: col.colNum,
                order: col.order,
                collapse: col.collapse,
                display: col.display
              }

              // group.column = this.transformToAvueOptions(col.children).column;
              group.column = col.children.column;
              data.group.push(group)
              data.column.splice(i, 1)
              i = i - 1;
            }
          }
          return data;

        },

        handlePreview2() {
          this.previewVisible = true;
        },

        changeUrl() {
          this.previewUrl = this.previewUrl + '&reload=' + new Date().toISOString();
        }
      }
    };
</script>

<style>
    .preview-box {
        width: 960px;
        margin: auto;
        height: 70vh;
        /*background: url("/static/img/11.png") no-repeat;*/
        background-size: 438px 70vh;
        padding: 40px 0 0 59px;
    }

    .preview-box iframe{
        width: 900px;;height:80vh;border: 0px
    }


    .phone-preview-box {
        width: 560px;
        margin: auto;
        height: 70vh;
        /*background: url("/static/img/11.png") no-repeat;*/
        background-size: 438px 70vh;
        padding: 40px 0 0 59px;
    }

    .phone-preview-box iframe{
        width: 500px;;height:80vh;border: 0px
    }


    .myDesign .el-card__body{
      padding: 0px!important;
    }

</style>
<style lang="scss" scoped>

    .ai-input-with-select{
        width: 80%;
    }


    .basic-container {
        /*padding: 0px 0px!important;*/
        box-sizing: border-box;
    }

    .myDesign {
      padding: 0px!important;
    }

    .myDesign .el-card__body{
        padding: 0px!important;
    }

    .avue-form-design {
      /***
          时间范围控件样式问题
  */
      .el-date-editor--daterange {
        padding: 0 0px !important;
      }

      .el-date-editor--datetimerange {
        padding: 0 0px !important;
      }

      /*.avue-date{*/
      /*    height: 32px!important;*/
      /*}*/
      /*.avue-time{*/
      /*    height: 32px!important;*/
      /*}*/

      /*.avue-select{*/
      /*    margin-bottom: 1.3667px;*/
      /*}*/

      /*.avue-input-number{*/
      /*    margin-bottom: 1.3667px;*/
      /*}*/

    }



    [class*="el-col-"]{
        float: left !important;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }

    .webapp {
        background-color: #fff;
        position: relative;
        width: 100%;
        height: 100%;

        .form-designer {
            height: 800px;
            overflow-y: scroll;


        }


        .form-designer .widget-config-container .el-tabs__header {
            position: relative;
        }



    }

    .design-upload-file {
      position: relative;
      width: 50px;
      padding: 10px 15px;
      border: 1px solid var(--el-color-primary);
      border-radius: 5px;
      background-color: var(--el-color-primary);
      color: #333333;
      font-size: 14px;
      text-align: center;
      overflow: hidden;
    }

    .design-upload-file span{ //单行显示
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    .design-upload-file:hover{ //简单的hover效果
      font-size: 15px;
      border-color:var(--el-button-text-color);
    }

    .design-upload-file input{
      height: 100%;
      width: 100%;
      position: absolute; //设置为绝对定位，不会影响到其他元素
      top: 0;
      right: 0;
      opacity: 0;   //透明度为0
      filter: alpha(opacity=0);
      cursor: pointer;
    }
</style>
